<template>
    <div v-loading="loading">
        <!-- 表格栏 -->
        <el-table
        class="cm-table__tb"
        :data="data.records"
        v-bind="$attrs"
        @selection-change="selectionChange"
        
        highlight-current-row
        :empty-text="t('table.empty')"
        style="width: 100%"
        >
            <el-table-column
            v-for="column in columns"
            :key="column.prop"
            v-bind="column"            
            :resizable="false"   
            align="center"
            >
                <template v-if="column.isImage" #default="{ url }">
                    <el-image
                    style="width: 50px; height: 50px"
                    :src="url || 'https://bpic.51yuansu.com/pic2/cover/00/32/33/5810ea612ebb2_610.jpg'" 
                    fit="cover">
                        <template #error>
                            图片找不到了
                        </template>
                    </el-image>
                </template>
            </el-table-column>
                
            <el-table-column
            v-if="showOperation"
            fixed="right"
            :label="t('action.operation')"
            :resizable="false"            
            min-width="160"
            align="center"          
            >
                <template #default="{ row }">
                    <template v-for="(opr, i) in operations" :key="i">
                        <template v-if="isShow(opr.show, row)">
                            <el-button
                            v-if="opr.type === 'edit'"
                            type="primary"
                            :disabled="isDisabled(opr.disabled, row)"
                            @click="handleEdit(row)"
                            >{{ t('action.edit') }}</el-button>

                            <el-button
                            v-else-if="opr.type === 'delete'"
                            type="danger"
                            :disabled="isDisabled(opr.disabled, row)"
                            @click="handleDelete(row)"
                            >{{ t('action.delete') }}</el-button>

                            <el-button
                            v-else
                            type="info"
                            :disabled="isDisabled(opr.disabled, row)"  
                            @click="opr.onClick(row)"
                            >{{ opr.label }}</el-button>
                        </template>
                    </template>
                </template>
            </el-table-column>
        </el-table>        

        <!-- 分页栏 -->
        <div class="cm-table__toolbar">
            <el-button
            v-if="showBatchDelete"
            type="danger"
            :disabled="selections.length === 0"
            @click="handleBatchDelete"
            >{{ t("action.batchDelete") }}</el-button>
            
            <el-pagination
            class="cm-table__pagination"
            v-if="showPagination"
            v-model:currentPage="pageRequest.pageNo"
            v-model:page-size="pageRequest.pageSize"
            :page-sizes="[10, 20, 30, 40, 50]"
            layout="total, prev, pager, next, sizes, jumper"
            :total="data.totalSize || 0"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            ></el-pagination>
        </div>          
    </div>
</template>

<script setup>
import { ElMessage } from "element-plus"

const { t } = useI18n()

const props = defineProps({
    getPage: Function,
    filters: Object,
    columns: Array,
    showPagination: {
        type: Boolean,
        default: true
    },
    showOperation: {
        type: Boolean,
        default: true
    },
    operations: {
        type: Array,
        default: () => {
            return [
                {
                    type: 'edit',
                },
                {
                    type: 'delete'
                }
            ]
        }
    },
    oprWidth: {
        type: Number,
        default: 185,
    },
    showBatchDelete: {
        typeof: Boolean,
        default: true
    }
})
const emit = defineEmits(['handleEdit', 'handleDelete'])

function isShow(showFn, row) {
    if (showFn && typeof showFn === 'function') {
        return showFn(row)
    }

    return true
}

function isDisabled(disabledFn, row) {
    if (disabledFn && typeof disabledFn === 'function') {
        return disabledFn(row)
    }

    return false
}

function handleEdit(row) {
    emit("handleEdit", row)
}

function handleDelete(row) {
    onDelete(row.id)
}

const selections = ref([])
function selectionChange(slts) {
    selections.value = slts
}

function handleBatchDelete() {
    let ids = selections.value.map((item) => item.id).toString()
    onDelete(ids)
}

function onDelete(ids) {
    ElMessageBox.confirm(t('tips.deleteConfirm'), t('tips.deleteTitle'), {
        confirmButtonText: t('action.confirm'),
        cancelButtonText: t('action.cancel'),
        type: 'warning',
        draggable: true
    }).then(() => {
        const callback = () => {
            ElMessage({message: t('tips.success'), type: "success"})
            reload()
        }
        emit("handleDelete", ids, callback)
    }).catch(() => {})
}

const loading = ref(false)
const pageRequest = reactive({
    pageNo: 1,
    pageSize: 10,
})
const data = ref({})

function findPage() {
    if (!props.getPage) {
        return
    }

    loading.value = true
    const req = props.getPage({ ...pageRequest, ...(props.filters || {}), sortby: props.sortby})
    if (Object(req).constructor === Promise) {
        req.then((res) => {
            if (res.data instanceof Array) {
                data.value = {
                    records: res.data,
                    totalSize: res.data.length
                }
            } else {
                data.value = res.data
            }
        }).catch(() => {
            data.value = {}
        }).finally(() => {
            loading.value = false
        })
    }
}

function reload() {
    handlePageChange(1)
}

function handleSizeChange(pageSize) {
    pageRequest.pageSize = pageSize
    pageRequest.pageNo = 1
    findPage()
}

function handlePageChange(pageNo) {
    pageRequest.pageNo = pageNo
    findPage()
}

reload()

defineExpose({
    refresh: findPage,
    reload,
})
</script>

<style lang="scss" scoped>
.cm-table__tb {
    border: 1px solid #eee;
    border-bottom: none;
    width: 100%;
}
.cm-table__toolbar {
    padding: 10px 5px;
    &::after {
        content: "";
        display: table;
        clear: both;
    }
}
.cm-table__pagination {
    float: right;
    padding-right: 0;
}
.danger {
    color: var(--el-color-danger) !important;
}
</style>